import numpy as np
from sklearn.preprocessing import OrdinalEncoder


def safe_inverse_transform(encoder, values):
    # valid_mask = np.isin(values, encoder.categories_[0])
    # if not np.all(valid_mask):
    #     invalid = np.unique(values[~valid_mask])
    #     print(f"替换未见标签: {invalid}")
    #     values[~valid_mask] = encoder.categories_[0][0]
    # return encoder.inverse_transform(values.reshape(-1, 1)).flatten()
    valid_indices = np.isin(values, encoder.classes_)
    if not np.all(valid_indices):
        invalid_values = values[~valid_indices]
        print(f"警告：发现未见标签 {invalid_values}，将替换为默认值")
        values[~valid_indices] = encoder.classes_[0]
    return encoder.inverse_transform(values.astype(int))
